﻿using chudb;
using ExcelConfig.StoreAPI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using xlstool;

namespace sametexts_u8
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ConfigStoreHelper.EnterConfigStoreAPIConfig();

            using var local = ChuDB.Open("cache.db");
            var sp = local.TakeSpace("sames");
            sp.EnsureIndex("IX_tag", "$.tag");
            var matchs = local.TakeSpace("matchs");

            var sames = new List<string>();
            var tags = new List<string>();
            foreach (var item in sp.FindAll())
            {
                if (tags.Contains(item["tag"]))
                {
                    if (! sames.Contains(item["tag"])) sames.Add(item["tag"]);
                    continue;
                }
                tags.Add(item["tag"]);
            }


            var xls = new Excel2003File();
            var sheet = xls.GetWorkbook().ToSheet("相似");
            var rowno = 1;
            var row = sheet.ToRow(rowno++);
            row.ToCell("A").SetValue("id");
            row.ToCell("B").SetValue("存货编码");
            row.ToCell("C").SetValue("规格型号");
            

            foreach (var item in sames)
            {
                var items = sp.FindAll(Query.EQ("tag", item));
                foreach (var _item in items)
                {
                    row = sheet.ToRow(rowno++);
                    row.ToCell("A").SetValue(_item["tag"].AsString);
                    row.ToCell("B").SetValue(_item["_id"].AsString);
                    row.ToCell("C").SetValue(_item["std"].AsString);
                }
            }

            using (var f2 = File.Create(Guid.NewGuid()+".xls")) xls.ToStream(f2);
        }
        internal static void loadu8(ChuSpace sp, ChuSpace matchs)
        {
            using (var db = new U8DB())
            {
                var x = db.ReadInventoryList();
                foreach (var item in x)
                {
                    sp.Goto(item.cInvCode);
                    var tag = TextCapsule.tag(item.cInvStd);
                    sp.Store("tag", tag);
                    sp.Store("std", item.cInvStd);
                    var count = sp.FindAll(Query.EQ("tag", "tag")).Count();
                    if (count > 1)
                    {
                        matchs.Goto(tag);
                        matchs.Store("count", count);
                    }
                }
            }
        }
    }
}
